import {
	BASE_URL,IMG_URL,DEBUG,API_URL
} from '@/env.js';

// const DEBUG = true;

 

export const myRequest = (options) => {
	return new Promise((resolve, reject) => {
		options.data.token = uni.getStorageSync("userInfo").token || "";
		let url_c = options.url_c ? "" : API_URL;
		uni.request({
			url: BASE_URL + url_c + options.url,
			method: options.type || 'GET',
			data: options.data || {},
			dataType: 'json',
			header: options.header || {
				"Content-Type": "application/x-www-form-urlencoded",
			},
			success: (res) => {
				let resource = res.data;
				if (resource.code != 1) {
					if (resource.code == 401) {
						uni.removeStorageSync('userInfo');
						uni.reLaunch({
							url: "/pages/member/login"
						})
					}
					if (options.showToast > 0) {
						return uni.showToast({
							title: resource.msg || '获取数据失败',
							icon: 'none'
							// icon: 'error'
						})
					}
				} else if (resource.code == 1 && options.showToast == 2) {
					uni.showToast({
						title: resource.msg,
						icon: 'success'
					})
				}
				resolve(resource);
			},
			fail: (err) => {
				uni.showToast({
					title: '请求接口失败'
				});
				reject(err);
			}
		})
	});
}

export const jumpUrl = (str, type) => {
	switch (type) {
		case 'tabBar':
			uni.switchTab({
				url: str
			});
			break;
		case 'redirectTo':
			uni.redirectTo({
				url: str
			});
			break;
		case 'tel':
			uni.makePhoneCall({
				phoneNumber: str
			});
			break;
		case 'showToast':
			return uni.showToast({
				title: str || '敬请期待',
				icon: 'none'
			})
			break;
		case 'navigateBack':
			return uni.navigateBack({
				delta: parseInt(str),
			})
			break;
		case 'reLaunch':
			return uni.reLaunch({
				url: str
			})
			break;
		case 'browser':
			// #ifdef APP-PLUS
			if (str.startsWith("tel:")) {
				this.makePhoneCall(str.replace('tel:', ''));
			} else {
				plus.runtime.openURL(str);
			}
			// #endif
			// #ifdef H5
			window.open(str)
			// #endif
			break;
		default:
			uni.navigateTo({
				url: str
			});
	}
}

export const copyText = (text) => {
	uni.setClipboardData({
		data: text,
		success: function () {
			uni.showToast({
				icon: 'none',
				title: '复制成功'
			})
		},
		fail: function () {
			uni.showToast({
				icon: 'error',
				title: '复制失败'
			})
		}
	});
}

export const updateArray = (myArray,newElement) => {
  if (myArray.includes(newElement)) {
    // 如果新元素已经存在于数组中，则从数组中删除它
    myArray = myArray.filter(item => item !== newElement);
  } else {
    // 如果新元素不存在于数组中，则将它添加到数组中
    myArray.push(newElement);
  }
  return myArray
}

export const setLogs = (options) => {
	var logs = uni.getStorageSync("logs");
	var now = new Date();
	var createtime = now.getFullYear() + "-" + now.getMonth() + 1 + "-" + now.getDate() + " " + now.getHours() +
		":" + now.getMinutes() + ":" + now.getSeconds();
	var tmp = {
		"title": options.title,
		"createtime": createtime,
		"content": options.data
	};
	if (logs.length > 0) {
		console.log(logs)
		logs.unshift(tmp)
		console.log("写入完成", logs)
	} else {
		logs = [tmp]
	}
	console.log("保存", logs)
	uni.setStorageSync('logs', logs)
}


export const customDate = (format,timestamp) => {
    const date = new Date(parseInt(timestamp) * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    format = format.replace('Y', year);
    format = format.replace('m', month);
    format = format.replace('d', day);
    format = format.replace('H', hours);
    format = format.replace('i', minutes);
    format = format.replace('s', seconds);

    return format;
}


export const getQueryString = (name) => {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    };
    return null;
}


export const integerToAlphaBase26 = (num) => {
    const alphaBase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let letters = '';

    while (num > 0) {
        const remainder = num % 26;
        if (remainder === 0) {
            letters = alphaBase[25] + letters; // 当余数为0时，设置当前字母为Z
            num = (num - 26) / 26; // 余数为0时，将num减去26并向下取整，以便处理上一位字母
        } else {
            letters = alphaBase[remainder - 1] + letters;
        }
        num = Math.floor(num / 26);
    }

    return letters;
}